package com.antdant.aspect;

import com.antdant.annotation.RequireLogin;
import com.antdant.entity.User;
import com.antdant.exception.GeneralException;
import com.antdant.exception.NeedLoginException;
import com.antdant.service.LoginService;
import com.antdant.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Author Lee Yunc
 * @Date 2021/2/24 20:45
 * @Description: 切面类
 * @Version 1.0
 */
@Slf4j
@Component
@Aspect
public class RequireLoginAspect {

    @Resource
    private LoginService loginService;

    @Pointcut("@annotation(com.antdant.annotation.RequireLogin)")
    public void annotationPointCut() {
        log.info("执行annotationPointCut方法");
    }

    @Around("annotationPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //log.info("执行doAround方法");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (DataUtils.isNull(attributes)) {
            log.error("attributes is null ");
            throw new GeneralException("服务器开小差了，请稍后重试");
        }
        HttpServletRequest request = attributes.getRequest();
        String methodName = joinPoint.getSignature().getName();
        Class<?> classTarget = joinPoint.getTarget().getClass();
        Class<?>[] par = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        Method objMethod = classTarget.getMethod(methodName, par);
        RequireLogin requireLogin = objMethod.getAnnotation(RequireLogin.class);
        String token = loginService.getUserTokenHeader(request);
        if (DataUtils.isNotNull(requireLogin) && requireLogin.required()) {
            User user = loginService.getLoginUser(token);
            if (DataUtils.isNull(user)) {
                log.error("need login for ip:{}", request.getRemoteHost());
                throw new NeedLoginException("需要登录，请先登录");
            }
        }
        if (DataUtils.isNotEmptyStr(token)) {
            loginService.refreshLoginUserExpire(token);
        }
        return joinPoint.proceed();
    }
}
